﻿#region License
//  Distrubted Under the GNU Public License version 2 (GPLv2)
// ========================================
// 
//  QuizzMasterStudio Version 3 
//  Copyright © 2012 , The Sparks (Autism App Jam 2014)
//  All rights reserved.  
// 
// Robert Long, Zephyr Yao, Hillary Chansavang, Li Xiao, Arial Xiao
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//  
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//  The full license is also included in the root folder.
// 
// Robert Long
//  Email: rbtLong@live.com
#endregion

using System;
using System.Windows.Threading;

namespace Core.Util
{
    public class RangedTimer
    {
        private readonly TimeSpan _interval = TimeSpan.FromMilliseconds(800);
        private readonly DispatcherTimer _tmr = new DispatcherTimer();
        private readonly Random _rnd = new Random();
        private readonly int _maxDelta = 2420;

        public bool IsEnabled { get { return _tmr.IsEnabled; }}
        public double Delta
        {
            get { return _rnd.Next(0, _maxDelta); }
        }
        public TimeSpan Interval { get { return _interval; } }

        public event EventHandler Tick = delegate { };

        public RangedTimer()
        {
            _tmr.Interval = generateInterval();
        }

        public RangedTimer(int interval, int max)
        {
            _interval = TimeSpan.FromMilliseconds(interval);
            _maxDelta = max;
            _tmr.Interval = generateInterval();
            _tmr.Tick += _tmr_Tick;
        }

            void _tmr_Tick(object sender, EventArgs e)
            {
                _tmr.Interval = generateInterval();
                Tick(this, e);
            }

                TimeSpan generateInterval()
                {
                    return Interval.Add(TimeSpan.FromMilliseconds(Delta));
                }

        public void Start()
        {
            _tmr.Start();
        }

        public void Stop()
        {
            _tmr.Stop();
        }

    }
}
